﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using UnityEngine;

namespace DashFire
{
  class ChannelConfig
  {
    public static bool s_IsShowConformTip = false;
    public static string s_ForceDownloadUrl = string.Empty;
    public static void Load(string iniFile, byte[] buffer)
    {
      ConfigFile m_IniFile = new ConfigFile(iniFile, buffer);
      s_IsShowConformTip = bool.Parse(m_IniFile.GetSetting("Config", "IsShowConformTip").Trim().ToLower());
      s_ForceDownloadUrl = m_IniFile.GetSetting("Config", "ForceDownloadUrl");
    }
  }
	class ChannelConfigLoader
	{
    public static ResAsyncInfo RequestChannelConfig()
    {
      ResAsyncInfo info = new ResAsyncInfo();
      info.CurCoroutine = CoroutineProxy.Instance.StartCoroutine(RequestChannelConfigAsync(info));
      return info;
    }
    public static IEnumerator RequestChannelConfigAsync(ResAsyncInfo info)
    {
      if (Application.internetReachability == NetworkReachability.NotReachable) {
        ResLoadHelper.Log("RequestChannelConfig network not reachable:");
        info.IsError = true;
        ResUpdateControler.s_UpdateError = ResUpdateError.Network_Error;
        yield break;
      }

      ResUpdateCallback.OnStartRequestChannelConfig();
      string requestChannelConfigUrl = ResLoadHelper.GetDynamicUrl(GameConfig.s_ChannelConfigUrl);
      ResLoadHelper.Log("RequestChannelConfig URL;" + requestChannelConfigUrl);
      using (WWW tWWW = new WWW(requestChannelConfigUrl)) {
        yield return tWWW;
        try {
          if (tWWW.error != null || (tWWW.text != null && tWWW.text.ToLower().Contains("<html"))) {
            ResLoadHelper.Log("RequestChannelConfig error");
            info.IsError = true;
            ResUpdateControler.s_UpdateError = ResUpdateError.RequestChannelConfig_WWW_Error;
            tWWW.Dispose();
            yield break;
          }
          byte[] bytes = tWWW.bytes;
          if (bytes == null || bytes.Length == 0) {
            ResLoadHelper.Log("RequestChannelConfig bytes null or empty data;");
            info.IsError = true;
            ResUpdateControler.s_UpdateError = ResUpdateError.RequestChannelConfig_Byte_Error;
            tWWW.Dispose();
            yield break;
          }
          ChannelConfig.Load(requestChannelConfigUrl, bytes);
        } catch (System.Exception ex) {
          ResLoadHelper.Log("RequestChannelConfig ex:" + ex);
          info.IsError = true;
          ResUpdateControler.s_UpdateError = ResUpdateError.RequestChannelConfig_Save_Error;
          yield break;
        } finally {
          tWWW.Dispose();
        }
      }
      ResUpdateCallback.OnEndRequestChannelConfig();

      info.IsDone = true;
      info.Progress = 1.0f;
    }
	}
}
